import 'dart:math';
import 'dart:typed_data';
import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:pointycastle/digests/sha256.dart';
import 'package:pointycastle/key_derivators/pbkdf2.dart';
import 'package:pointycastle/key_derivators/api.dart';
import 'package:pointycastle/macs/hmac.dart';
import 'package:pointycastle/ecc/api.dart';
import 'package:pointycastle/ecc/curves/secp256k1.dart';
import 'package:hex/hex.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/random/fortuna_random.dart';
import 'package:pointycastle/key_generators/api.dart';


class GenKeyLogic extends GetxController {
  final result = ''.obs;
  final pwdController = TextEditingController();
  // 在 HomeLogic 类中新增以下变量
  final key1 = Uint8List(0).obs;    // 存储 PBKDF2 生成的 key1
  final key2 = Uint8List(0).obs;    // 存储随机生成的 key2
  final iv = encrypt.IV.fromLength(16).obs; // 存储加密 IV
  String cipherText = '';            // 存储加密后的 cipher

  void generateAESKey() async {
    try {
      if (!validatePassword(pwdController.text)) return;
      EasyLoading.show(status: '生成中...');

      // 生成 key1（PBKDF2）
      final pwd = pwdController.text;
      print("pwd = $pwd");
      final salt = encrypt.IV.fromSecureRandom(8);
      final hmac = HMac(SHA256Digest(), 64);
      final derivator = PBKDF2KeyDerivator(hmac)
        ..init(Pbkdf2Parameters(salt.bytes, 1000, 32));
      final key1Bytes = derivator.process(Uint8List.fromList(utf8.encode(pwd)));

      // ✅ 方案1：使用 Dart 原生安全随机生成 key2
      final key2Bytes = Uint8List(32);
      final random = Random.secure();
      for (int i = 0; i < key2Bytes.length; i++) {
        key2Bytes[i] = random.nextInt(256);
      }

      // 使用 key1 加密 key2
      final iv = encrypt.IV.fromSecureRandom(16);
      // ✅ 确保 key1Bytes 是 Uint8List
      final keyBytes = key1Bytes is Uint8List
          ? key1Bytes
          : Uint8List.fromList(key1Bytes);

      // ✅ 正确构造 Key
      final aesKey = encrypt.Key(keyBytes);
      final encrypter = encrypt.Encrypter(encrypt.AES(aesKey, mode: encrypt.AESMode.cbc));
      final encrypted = encrypter.encryptBytes(key2Bytes, iv: iv);

      // 存储到文件
      await _saveToFile('${salt.base64}|${iv.base64}|${encrypted.base64}');

      result.value = '''
    密码散列(PBKDF2)密钥pwdKey（不保存）:
    hex: ${hex.encode(key1Bytes)}
    base64: ${base64Encode(key1Bytes)}\n
    随机核心加密密钥aesKey（不保存）:
    hex: ${hex.encode(key2Bytes)}
    base64: ${base64Encode(key2Bytes)}\n
    pwdKey加密aesKey的密文结果（保存）:
    hex: ${hex.encode(encrypted.bytes)}
    base64: ${encrypted.base64}\n
    生成pwdKey的盐值salt（保存）:
    hex: ${hex.encode(salt.bytes)}
    base64: ${salt.base64}\n
    参与加解密的初始化向量iv（保存）：
    hex: ${hex.encode(iv.bytes)}
    base64: ${iv.base64}
    ''';

    } catch (e) {
      result.value = '生成失败：${e.toString()}';
    } finally {
      EasyLoading.dismiss();
    }
    print(result.value);
  }

  Future<void> _saveToFile(String content) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/keystore.bin');
      await file.writeAsString(content);
      print('文件保存成功: ${file.path}');
    } catch (e) {
      throw Exception('文件保存失败: $e');
    }
  }

  void decryptKey2() async {
    try {
      if (!validatePassword(pwdController.text)) return;
      EasyLoading.show(status: '解密中...');

      // 从文件读取数据
      final cipherData = await _readFromFile();
      final parts = cipherData.split('|');
      if (parts.length != 3) throw Exception('文件格式错误');

      // 解析盐值、IV、密文
      final salt = encrypt.IV.fromBase64(parts[0]); // 🚨 关键：使用存储的盐值
      final iv = encrypt.IV.fromBase64(parts[1]);
      final cipher = encrypt.Encrypted.fromBase64(parts[2]);

      // 重新生成key1（必须使用相同盐值）
      final pwd = pwdController.text;
      final hmac = HMac(SHA256Digest(), 64);
      final derivator = PBKDF2KeyDerivator(hmac)
        ..init(Pbkdf2Parameters(salt.bytes, 1000, 32));
      final key1Bytes = derivator.process(
          Uint8List.fromList(utf8.encode(pwd))
      );

      // 解密操作
      final encrypter = encrypt.Encrypter(encrypt.AES(encrypt.Key(key1Bytes), mode: encrypt.AESMode.cbc));
      final decrypted = encrypter.decryptBytes(cipher, iv: iv);

      result.value = '''
    解密成功！
    Key2: ${base64Encode(decrypted)}
    ''';

    } catch (e) {
      result.value = '解密失败: ${e.toString()}';
    } finally {
      EasyLoading.dismiss();
    }
  }
  Future<String> _readFromFile() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/keystore.bin');
      if (!await file.exists()) throw Exception('文件不存在');
      return await file.readAsString();
    } catch (e) {
      throw Exception('文件读取失败: $e');
    }
  }

  void generateECCKeyPair() {
    try {
      EasyLoading.show(status: '生成中...');

      final keyPair = _generateKeyPair();
      result.value = '私钥：${keyPair.privateKey}\n公钥：${keyPair.publicKey}';
    } catch (e) {
      result.value = '生成失败：${e.toString()}';
    } finally {
      EasyLoading.dismiss();
    }
    print(result.value);
  }

  KeyPair _generateKeyPair() {
    // 手动创建曲线参数
    final curve = ECCurve_secp256k1();
    final domainParams = ECDomainParameters('secp256k1');

    final generator = domainParams.G;
    final n = domainParams.n;

    final rand = Random.secure();
    final d = _generatePrivateKey(n!, rand);
    final Q = generator * d;

    return KeyPair(
        privateKey: HEX.encode(_bigIntToBytes(d)),
        publicKey: HEX.encode(_encodePoint(Q!))
    );
  }

  Uint8List _encodePoint(ECPoint point) {
    return point.getEncoded(false);
  }

  Uint8List _bigIntToBytes(BigInt number) {
    var bytes = (number.bitLength + 7) ~/ 8;
    var b256 = BigInt.from(256);
    var result = Uint8List(bytes);
    for (var i = 0; i < bytes; i++) {
      result[bytes - 1 - i] = (number % b256).toInt();
      number = number ~/ b256;
    }
    return result;
  }

  BigInt _generatePrivateKey(BigInt n, Random rand) {
    final numBytes = (n.bitLength + 7) ~/ 8;
    BigInt d;
    do {
      final privateKeyBytes = Uint8List(numBytes);
      for (var i = 0; i < numBytes; i++) {
        privateKeyBytes[i] = rand.nextInt(256);
      }
      d = _bytesToBigInt(privateKeyBytes);
    } while (d >= n || d == BigInt.zero);
    return d;
  }

  BigInt _bytesToBigInt(Uint8List bytes) {
    BigInt result = BigInt.zero;
    for (var i = 0; i < bytes.length; i++) {
      result = result * BigInt.from(256) + BigInt.from(bytes[i]);
    }
    return result;
  }

  bool validatePassword(String pwd) {
    if (pwd.length < 8 || pwd.length > 20) {
      EasyLoading.showError('密码必须为8-20位');
      return false;
    }
    return true;
  }
}

class KeyPair {
  final String privateKey;
  final String publicKey;

  KeyPair({required this.privateKey, required this.publicKey});
}